/************************************************************************
                                                                     
   Xceed Ultimate ListBox for Silverlight                                                                                                                                            
   Copyright (C) 2010 Xceed Software Inc.    
                                                                     
   This program is provided to you under the terms of the GNU General Public  
   License version 2 as published by the Free Software Foundation. 
        
   This program is distributed in the hope that it will be useful, but
   WITHOUT ANY WARRANTY, without even the implied warranty of 
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   General Public License for more details.

   You should have received a copy of the GNU General Public License along 
   with this program, if not, write to the Free Software Foundation, Inc., 
   51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

   This program can be provided to you by Xceed Software Inc. under a
   proprietary commercial license agreement for use in non-Open Source
   projects. Visit Xceed.com to find the commercial edition of 
   Xceed Ultimate ListBox for Silverlight.                                    
                                                                      
 **********************************************************************/

using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Diagnostics;

namespace Xceed.Silverlight.Data
{
  internal class ConversionEnumerator<T> : AsyncParentEnumerator<T>
  {
    #region Static Fields

    private static Guid JumpMoveAndFetchCallId = DataUtils.CreateCallId();

    #endregion Static Fields


    internal ConversionEnumerator(
      IAsyncEnumerator childEnumerator,
      Func<object, T> converter,
      Func<T, object> convertBack )
      : base( childEnumerator )
    {
      m_convert = converter;
      m_convertBack = convertBack;
    }


    #region Convert Property

    public Func<object, T> Convert
    {
      get
      {
        return m_convert;
      }

      set
      {
        if( m_convert != null )
          throw new InvalidOperationException( "An attempt was made to set a Convert function when one has already been provided." );

        m_convert = value;
      }
    }

    #endregion Convert Property

    #region ConvertBack Property

    public Func<T, object> ConvertBack
    {
      get
      {
        return m_convertBack;
      }

      set
      {
        if( m_convertBack != null )
          throw new InvalidOperationException( "An attempt was made to set a ConvertBack function when one has already been provided." );

        m_convertBack = value;
      }
    }

    #endregion ConvertBack Property


    public override JumpMoveAndFetchAsyncResult BeginJumpMoveAndFetch(
      JumpMoveAndFetchParameters parameters,
      AsyncCallback userCallback,
      object asyncState )
    {
      JumpMoveAndFetchAsyncResult asyncResult = new JumpMoveAndFetchAsyncResult(
                                                  ConversionEnumerator<T>.JumpMoveAndFetchCallId,
                                                  userCallback,
                                                  asyncState,
                                                  parameters );

      parameters = parameters.CreateWithNewSourcePosition(
        this.ConvertSourcePosition(
          parameters.SourcePosition,
          parameters.ExpectedMoveCount,
          parameters.ExpectedFetchCount )
          );

      asyncResult.Start(
        ( callback, state ) => this.ChildEnumerator.BeginJumpMoveAndFetch(
                                 parameters,
                                 callback,
                                 state ),
        ( parentAr, ar ) => new DependentCallResult(
                              this.ChildEnumerator.EndJumpMoveAndFetch(
                                ( JumpMoveAndFetchAsyncResult )ar ) ) );
      return asyncResult;
    }

    public override JumpMoveAndFetchResult<T> EndJumpMoveAndFetch( 
      JumpMoveAndFetchAsyncResult jumpMoveAndFetchAsyncResult )
    {
      jumpMoveAndFetchAsyncResult.ValidateCallEnd( ConversionEnumerator<T>.JumpMoveAndFetchCallId );

      JumpMoveAndFetchResult mfr = jumpMoveAndFetchAsyncResult.GetCallResult<JumpMoveAndFetchResult>();

      return this.ConvertJumpResult( jumpMoveAndFetchAsyncResult, mfr );
    }

    protected virtual JumpMoveAndFetchResult<T> ConvertJumpResult( 
      JumpMoveAndFetchAsyncResult jumpMoveAndFetchAsyncResult, 
      JumpMoveAndFetchResult childResult )
    {
      SourcePosition endPosition = childResult.EndPositionObject;

      if( endPosition is ItemPosition )
      {
        endPosition = new ItemPosition( ConvertItem( ( ( ItemPosition )endPosition ).Item ) );
      }

      return new JumpMoveAndFetchResult<T>(
                   jumpMoveAndFetchAsyncResult,
                   childResult.ActualMoveCount,
                   this.ConvertList( childResult.FetchedObjects ),
                   childResult.Result,
                   endPosition,
                   childResult.EndPositionOffset,
                   childResult.TotalCount );
    }

    protected virtual SourcePosition ConvertSourcePosition( 
      SourcePosition sourcePosition, 
      long expectedMoveCount, 
      int expectedFetchCount )
    {
      if( sourcePosition is ItemPosition )
      {
        sourcePosition = new ItemPosition(
                           this.ConvertBackItem(
                             ( T )( ( ItemPosition )sourcePosition ).Item ) );
      }

      return sourcePosition;
    }

    protected virtual T ConvertItem( object item )
    {
      return m_convert( item );
    }

    protected virtual object ConvertBackItem( T item )
    {
      return m_convertBack( item );
    }

    protected override void ChildDataChanged( DataChangedEventArgs args )
    {
      object convertedNewItem = null;
      object convertedOldItem = null;
      ItemChangedInfo itemChangedInfo = null;

      if( args.Action == DataChangedAction.Add
        || args.Action == DataChangedAction.Replace )
      {
        convertedNewItem = this.ConvertItem( args.NewItem );
      }

      if( args.Action == DataChangedAction.Remove
        || args.Action == DataChangedAction.Replace )
      {
        convertedOldItem = this.ConvertItem( args.OldItem );
      }

      if( args.Action == DataChangedAction.ItemChanged )
      {
        itemChangedInfo = args.ItemChangedInfo.CreateWithNewTarget( 
          this.ConvertItem( args.ItemChangedInfo.Target ) );
      }

      base.ChildDataChanged(
        new DataChangedEventArgs(
          args.Action,
          convertedNewItem,
          convertedOldItem,
          args.RemovePosition,
          args.NewCurrentPosition,
          itemChangedInfo ) );
    }

    protected virtual ICollection<T> ConvertList( ICollection dataList )
    {
      if( dataList == null )
        return null;

      return ( from p in dataList.Cast<object>()
               select ConvertItem( p ) ).ToList();
    }


    #region Private Fields

    private Func<object, T> m_convert;      //null
    private Func<T, object> m_convertBack;  //null

    #endregion Private Fields
  }
}
